package yxy.cherry.router.server;

import yxy.apple.logger.Logger;
import yxy.apple.protobuf.Message.Parcal;
import yxy.banana.server.internal.InternalServerController;
import yxy.banana.socket.controlled.ChannelManager;
import yxy.cherry.router.Configuration;
import yxy.cherry.router.Reactor;

public class RouterServerController extends InternalServerController<RouterServerHandler> {

	private static final Logger logger = Logger.create(RouterServerController.class);
	private static final ChannelManager<RouterServerHandler> mapper = new ChannelManager<>();

	public RouterServerController() {
		super(Configuration.shared().TCPServer.HeartbeatTimeout, Configuration.shared().TCPServer.RegistryTimeout);
	}

	// 转发控制消息
	@Override
	public boolean control(Parcal parcal) throws Exception {
		if (super.control(parcal)) {
			return true;
		} else {
			return this.handler().transmit(parcal);
		}
	}

	@Override
	protected void registered(int system, int cluster) {
		String key = Reactor.instance.clustered().add(cluster, this.handler());
		this.handler().setKey(key);
		logger.info("注册请求处理成功，cluster:%d\r\n%s", cluster, this.toString());
	}

	@Override
	protected boolean register(int system, int cluster) {
		boolean result = false;
		if (system == this.handler().system() && cluster != 0) {
			result = true;
		} else {
			logger.error("注册请求信息有误（system:%d, cluster:%d)，注册无法完成，请检查请求发送端配置！\r\n%s", this.toString());
		}
		return result;
	}

	@Override
	protected void inactived() {
		super.inactived();
		// 失活时把通路移除
		String key = this.handler().key();
		if (key != null) {
			Reactor.instance.clustered().remove(key, this.handler());
			logger.info("连接失活移除，cluster:%s\r\n%s", key, this.toString());
		}
	}

	@Override
	protected ChannelManager<RouterServerHandler> manager() {
		return mapper;
	}

}
